package br.com.futibamanager.validator;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import br.com.futibamanager.util.Constants;
import br.com.futibamanager.util.FacesUtil;

/**
 * An e-mail validator.
 * 
 * @author diogenes.feijo
 *
 */
public class EmailValidator implements Validator {
	
	/**
	 * @see javax.faces.validator.Validator#validate(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.Object)
	 */
	@Override
	public void validate(FacesContext facesContext, 
						 UIComponent uiComponent, 
						 Object object) throws ValidatorException {
		
		if (object == null) {
			return;
		}
		
		String email = object.toString();
		
		if (!email.matches(Constants.EMAIL_REGEX)) {
			String errorMessage = 
				FacesUtil.getFormattedMessage("invalid.email", email);

			FacesMessage facesMessage = 
				new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMessage, null);

			throw new ValidatorException(facesMessage);
		}
	}

}
